#include <tsin/runtime/GameEventHandleWork.hpp>

#include <tsin/runtime/GameRuntime.hpp>
#include <tsin/library/Game.hpp>
#include <tsin/library/GameEvent.hpp>

#include <cstring>

using namespace tsin;

GameEventHandleWork::GameEventHandleWork()
{
        memset(events, 0, MAX_GAME_EVENTS * sizeof(GameEvent *));
}

GameEventHandleWork::~GameEventHandleWork()
{
}

void GameEventHandleWork::init(GameRuntime *runtime)
{
        this->runtime = runtime;
        nrEvents = runtime->game->getEvents(events);
        for (int i = 0, n = 0; i < MAX_GAME_EVENTS, n < nrEvents; i++) {
                if (events[i] == 0)
                        continue;
                events[i]->init(*runtime);
                n ++;
        }
}

int GameEventHandleWork::run()
{
        for (int i = 0, n = 0; i < MAX_GAME_EVENTS, n < nrEvents; i++) {
                if (events[i] == 0)
                        continue;
                if (events[i]->trigger(*runtime)) {
                        GameEvent *next = events[i]->handle(*runtime);
                        if (next != events[i]) {
                                delete events[i];
                                events[i] = next;
                        }
                }
                (events[i] == 0) ? (nrEvents --) : (n ++);
        }

        return 0;
}
